package org.lucas.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.lucas.vo.PhoneLocationApiResponseVO;
import com.fasterxml.jackson.databind.ObjectMapper;

@Data
@Slf4j
@AllArgsConstructor
public class PhoneLocationQueryUtil {

    private String accessUrl;

    private String secretId;

    private String secretKey;


//    {
//        "code": 200,
//            "haoduan": "1321993",
//            "shengfen": "四川",
//            "chengshi": "绵阳",
//            "fuwushang": "中国联通",
//            "quhao": "0816",
//            "qhdm": "510700",
//            "youbian": "621000"
//    }
//      {
//          "code": 400,
//          "msg": "用户被封禁！"
//      }

    public PhoneLocationApiResponseVO getPhoneLocation(Long phoneNumber) {
        PhoneLocationApiResponseVO vo = new PhoneLocationApiResponseVO();
        try {
            OkHttpClient client = new OkHttpClient();

            HttpUrl url = HttpUrl.parse(accessUrl)
                    .newBuilder()
                    .addQueryParameter("id", secretId)
                    .addQueryParameter("key", secretKey)
                    .addQueryParameter("phone", phoneNumber.toString())
                    .build();

            //log.info(url.toString());

            Request request = new Request.Builder()
                    .url(url)
                    .build();

            try (Response response = client.newCall(request).execute()) {

                String responseBody = response.body().string();

                //转换
                ObjectMapper objectMapper = new ObjectMapper();

                vo = objectMapper.readValue(responseBody, PhoneLocationApiResponseVO.class);
                log.info("返回的数据~~~~~~: " + vo);
            }
        } catch (Exception e) {
            log.error("Error: " + e.getMessage());
        }
        return vo;
    }

}
